﻿using Blazored.LocalStorage;
using BPM.Web.Shared.Constants;
using BPM.Web.Shared.Extensions;
using Microsoft.AspNetCore.Components.Authorization;

namespace BPM.Web.Shared.Auth
{
    public class JwtAuthenticationStateProvider : AuthenticationStateProvider
    {
        private readonly ILocalStorageService _storage;

        public JwtAuthenticationStateProvider(ILocalStorageService service) => _storage = service;

        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var accessToken = await _storage.GetItemAsStringAsync(StorageConstants.AccessToken);
            var refreshToken = await _storage.GetItemAsStringAsync(StorageConstants.RefreshToken);
            return new AuthenticationState(TokenExtensions.GetClaimsPrincipal(accessToken, refreshToken));
        }

        /// <summary>
        /// 更新授权信息
        /// </summary>
        /// <param name="accessToken">授权账票</param>
        /// <param name="refreshToken">刷新账票</param>
        /// <param name="notify">是否推送通知</param>
        /// <returns></returns>
        public async Task UpdateAuthenticated(string? accessToken, string? refreshToken, bool notify = true)
        {
            var user = TokenExtensions.GetClaimsPrincipal(accessToken, refreshToken);
            if (user.Identity?.IsAuthenticated == true)
            {
                await _storage.SetItemAsStringAsync(StorageConstants.AccessToken, accessToken);
                await _storage.SetItemAsStringAsync(StorageConstants.RefreshToken, refreshToken);
            }
            else
            {
                await _storage.RemoveItemAsync(StorageConstants.AccessToken);
                await _storage.RemoveItemAsync(StorageConstants.RefreshToken);
            }
            var authentication = new AuthenticationState(user);

            //通知推送
            if (notify)
            {
                NotifyAuthenticationStateChanged(Task.FromResult(authentication));
            }
        }
    }
}
